var customerTable = function() {
	var validator;
	return {
		init : function() {
			//初始化checkBox 初始化行点击选中
			var tableId = "customer_table";
			util.initCheckBox(tableId);
			//下拉框赋值
			util.getDictByParentKey("KHZTDM", 'id_cusStatus','全部');
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "cusCode",
					"value" : $("#id_cusCode").val().trim()
				});
				aoData.push({
					"name" : "cusName",
					"value" : $("#id_cusName").val().trim()
				});
				aoData.push({
					"name" : "status",
					"value" : $("#id_cusStatus").val()
				});
				$.ajax({
					"type" : "post",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			};
			$('#customer_table').DataTable({
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "main/customer/getCustomer.mvc",
				"fnServerData" : queryData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [ {
					"data" : "pkId",
					"render" : function(data, type, full, meta) {
						 return '<div class="checker" onclick="util.selectCheckBox(\'' + tableId + '\', this)"><span><input type="checkbox" class="checkboxes"/></span></div>';
					},
					"bSortable" : false
				},
				{
					"data" : "cusCode",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "parentCusName",
					"bSortable" : false,
					"defaultContent": ""
				}, 
				{
					"data" : "cusName",
					"bSortable" : false,
					"defaultContent": "",
					"render" : function(data, type, full, meta) {
							 return '<a class="showCusDetail" style="cursor:pointer;color:blue;" data-toggle="modal">'+data+'</a>';
						}
				},
				{
					"data" : "shortName",
					"bSortable" : false,
					"defaultContent": ""
				},

				{
					"data" : "city",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "province",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "impLevel",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "type",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "status",
					"bSortable" : false,
					"render" : function(data, type, full, meta) { 
						if("试用"==data){
							return "<span class=\"label label-success\">"+data+"</span>";
						}else if("潜在"==data){
							return "<span class=\"label label-info\">"+data+"</span>";
						} else if("高意向"==data) {
							return "<span class=\"label label-important\">"+data+"</span>";
						} else if("成交"==data) {
							return "<span class=\"label\">"+data+"</span>";
						} else {
							return null;
						}
					},
					"defaultContent": ""
				},
				{
					"data" : "address",
					"bSortable" : false,
					"visible" : false,  //隐藏列
					"defaultContent": ""
				},
				{
					"data" : "parentCusId",
					"bSortable" : false,
					"visible" : false,  //隐藏列
					"defaultContent": ""
				},
				{
					"data" : "zipCode",
					"bSortable" : false,
					"visible" : false,
					"defaultContent": ""
				}
				],
				"fnDrawCallback" : function(oSetting) {
					util.clearSelected(tableId);
				}
			});

			// 查询
			$("#btn_query").click(function(e) {
				debugger
				var table = $('#customer_table').DataTable();
				table.draw(true);
			});
		    // 重置
			$("#btn_reset").click(function() {
				$("#customer_search_form")[0].reset();
			});
			$(function(){
				$("#form_company_save").click(function(){
					validator = validateMyForm("customer_form");
					if(validator.form()){
						save();
					}else{
						return false;
					}
				});
				$('.search-body .my-input').bind('keyup', function(event) {
					if (event.keyCode == "13") {
						//回车执行查询
						$('.search-button #btn_query').click();
					}
				});
			});

			/**
			 * 获取上级单位
			 * @return {[type]} [description]
			 */
			function getParentCusOption(selectId,defaultOption,cusId) {
				$.ajax({
					"type" : "post",
					"url" :  "main/customer/getParentCusOption.mvc",
					"async" : false,
					"dataType" : "json",
					"data" : {"parentId":cusId},
					"success" : function(resp) {
						createOption(selectId, defaultOption, resp.dict);
					}
				});
				
			};

			/**
			 * 获取上级单位
			 * @return {[type]} [description]
			 */
			function getParentCusOptionExcludeSelf(selectId,defaultOption,cusId) {
				$.ajax({
					"type" : "post",
					"url" :  "main/customer/getParentCusOptionExcludeSelf.mvc",
					"async" : false,
					"dataType" : "json",
					"data" : {"cusId":cusId},
					"success" : function(resp) {
						createOption(selectId, defaultOption, resp.dict);
					}
				});
				
			};

			/**
		     * 创建下拉框选项
		     * @param selectId 下拉框输入id
		     * @param defaultOption 默认选择
		     * @param resp 下拉框值
		     */
			function createOption (selectId, defaultOption, data) {
		    	$("#"+selectId).empty();
				htmlStr = $("#"+selectId)[0].innerHTML;
				if(defaultOption !=undefined){
					if('请选择'==defaultOption||''==defaultOption){
						htmlStr +='<option value="" style="display:none">'+defaultOption+'</option>';
					} else {
						htmlStr +='<option value="" >'+defaultOption+'</option>';
					}
					
				}
				for (var i = 0; i < data.length; i++) {
					htmlStr += '<option value="' + data[i].value + '">' + data[i].name + '</option>';
				}
				$("#"+selectId).append(htmlStr);
		    };

			
			/*
			 * validate 自定义验证
			 */
			function validateMyForm(formId){
				return $( '#' + formId ).validate({  
					errorElement: 'em',
					errorClass: 'redStar',
					focusInvalid: false, 
					ignore: "",
			        rules:{  
			        	cusCode:'required',
			        	cusName:'required',
			        	shortName:'required',
			        	impLevel:'required',
			        	type:'required',
			        	zipCode:'checkZipCode'
			            },  
			        messages:{  
			        	cusCode:'不能为空',
			        	cusName:'不能为空',
			        	shortName:'不能为空',
			        	impLevel:'不能为空',
			        	type:'不能为空',
			        	zipCode:'邮编非法'
			            }, 
			            errorPlacement: function (error, element) { 
			            	//默认以span形式显示在输入框后
		                   error.insertAfter(element);
		                   $(element.next()).attr('title', $(error).text()).tooltip();
		                   $(error).text('');
		                }
			    });
			}
			$.validator.addMethod("checkZipCode",function(value,element,params){  
	            var checkZipCode = /^[0-9][0-9]{5}$/;  
	            return this.optional(element)||(checkZipCode.test(value));  
	        });
			//新增弹窗
			$("#customer_table_add").click(function(){
				$("#customer_add_title").text("新增客户");
				$("#company_id").val("");
				util.getDictByParentKey("KHLXDM", 'type','请选择');
				util.getDictByParentKey("ZYJBDM", 'impLevel','请选择');
				util.getDictByParentKey("KHZTDM", 'status','请选择');
				util.getDictByParentKey("SSHYDM", 'buss','请选择');
				util.getDictByParentKey("GSXZDM", 'companyNature','请选择');
				
				getParentCusOption("parent_custom","请选择",'');
				$("#parent_custom").removeAttr('disabled');
				//初始化省市联动下拉框
				$("#cityDiv").citySelect({  
					   nodata: "none",  
				       required: true,  
				       prov:"北京",  
				       city:"东城区",  
				       dist:""  
				}); 
				$("#add-customer").modal({show:true,keyboard:false});
			})
			
			//显示详情
			$("#customer_table").on("click", "a.showCusDetail",function(e){
				var c = util.getCheckedData("customer_table");
				if (c.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return false;
				}
				var d = [];
				d =getCustomerById(util.getCheckedData("customer_table")[0].pkId);
				$("#detail_cusCode").text(d.cusCode);
				$("#detail_cusName").text(d.cusName); 
				$("#detail_cusName").attr('title',d.cusName);
				$("#detail_shortName").text(d.shortName);
				$("#detail_parent_cus").text((d.parentCusName!=null)?d.parentCusName:'');
				$("#detail_shortName").attr('title',d.shortName);
				$("#detail_impLevel").text(d.impLevel);
				$("#detail_type").text(d.type);
				$("#detail_status").text((d.status!= null)? d.status:'');
				$("#detail_companyNature").text((d.companyNature!=null)?d.companyNature:'');
				$("#detail_buss").text((d.buss!=null)?d.buss:'');
				$("#detail_city").text((d.city!=null)?d.city:'');
				$("#detail_province").text((d.province!=null)?d.province:'');
				$("#detail_address").text((d.address!=null)?d.address:'');
				$("#detail_address").attr('title',d.address);
				$("#detail_zipCode").text((d.zipCode!=null)?d.zipCode:'');
				$("#addID-detail").modal({show:true,keyboard:false});
			});
			
			//保存
			function save(){
				var d = {};
				d['pkId'] = $("#company_id").val();
				d['cusCode'] = $("#cusCode").val();
				d['cusName'] = $("#cusName").val();
				d['shortName'] =  $("#shortName").val();
				d['province'] = $("#loc_province").find("option:selected").text();
				d['city'] = $("#loc_city").find("option:selected").text();
				d['area'] = $("#county").find("option:selected").text();
				d['impLevel'] = $("#impLevel").val();
				d['parentCusId'] = $("#parent_custom").val();
				d['parentCusName'] = $("#parent_custom").find("option:selected").text();
				d['type'] = $("#type").val();
				d['status'] = $("#status").val();
				d['companyNature'] = $("#companyNature").val();
				d['buss'] = $("#buss").val();
				d['zipCode'] = $("#zipCode").val();
				d['address'] = $("#address").val();
				var table = $('#customer_table').DataTable();
				$.ajax({
					"type" : "post",
					"url" : "main/customer/saveOrUpdateCustomer.mvc",
					"dataType" : "json",
					"async":false,
					"data" : d,
					"success" : function(resp) {
						if(resp.msg=='SUCCESS'){
							rmsBox.notify('success', {msg: '保存成功！'});
							$("#form_btn_close").click();
							table.draw(true);
						}else{
							rmsBox.notify('error', {msg: '保存失败！',delay:3000});
						}
						
					}
				});
			};
			
			// 修改
			$('#customer_table_edit').on('click', function(e) {
				debugger
				var d = [];
				d = util.getCheckedData("customer_table");
				if (d.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return false;
				}
				
				util.getDictByParentKey("KHLXDM", 'type','请选择');
				util.getDictByParentKey("ZYJBDM", 'impLevel','请选择');
				util.getDictByParentKey("KHZTDM", 'status','请选择');
				util.getDictByParentKey("SSHYDM", 'buss','请选择');
				util.getDictByParentKey("GSXZDM", 'companyNature','请选择');
				var cusId = util.getCheckedData("customer_table")[0].pkId;
				getParentCusOptionExcludeSelf("parent_custom"," ",cusId);
				
				//判断登录账号类型，若为客户用户则编辑时不允许修改上级客户
				$.ajax({
						"type" : "post",
						"url" : "main/sysUser/checkUserClass.mvc",
						"dataType" : "json",
						"async":false,
						"data" : '',
						"success" : function(resp) {
							//debugger
							if (resp.flag == 'true' && cusId == resp.cusId) {
								$("#parent_custom").attr({"disabled":"disabled"});
							}
						}
					});
				//								
				$("#customer_add_title").text("编辑客户");
				var d = [];
				d = getCustomerById(util.getCheckedData("customer_table")[0].pkId);
				$('#cusCode').val(d.cusCode);
				$('#cusName').val(d.cusName);
				$('#shortName').val(d.shortName);
				$("#cityDiv").citySelect({  
					nodata: "none",  
				    required: true,  
				    prov: d.province, //省份 
				    city: d.city, //城市 
				    dist: d.area //区域
				}); 
				$("#parent_custom option").each(function() {
					if(d.parentCusName == $(this).html()){
						$("#parent_custom").val($(this).val());
					}
				});
				$('#impLevel option').each(function () {
					if(d.impLevel ==  $(this).html()){
						$("#impLevel").val($(this).val());
					}
				});
				$('#companyNature option').each(function () {
					if(d.companyNature ==  $(this).html()){
						$("#companyNature").val($(this).val());
					}
				});
				$('#type option').each(function () {
					if(d.type ==  $(this).html()){
						$("#type").val($(this).val());
					}
				});
				$('#status option').each(function () {
					if(d.status ==  $(this).html()){
						$("#status").val($(this).val());
					}
				});
				$('#buss option').each(function () {
					if(d.buss ==  $(this).html()){
						$("#buss").val($(this).val());
					}
				});
				
				$('#zipCode').val(d.zipCode);
				$('#address').val(d.address);
				$("#company_id").val(d.pkId);
				$("#add-customer").modal({show:true,keyboard:false});
			});
			//关闭弹窗清空表单内容
			$("#form_btn_close").on("click", function(){
				$("#customer_form")[0].reset();
				if (validator) {
					validator.resetForm();
				}
			});
			//删除 -----begin
			$("#customer_table_del").on('click', function(){
				var d = [];
				d = util.getCheckedData("customer_table");
				if (d.length == 0) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
				} else {
					//检查所选择数据状态
					var d = [];
					d = util.getCheckedData("customer_table");
					var idArray=[];
					for (var i=0;i<d.length;i++) {
						idArray.push(d[i].pkId);
					}
					$.ajax({
						"type" : "post",
						"url" : "main/customer/checkCustomerStatus.mvc",
						"dataType" : "json",
						"async":false,
						"data" : {
							"pkId" : idArray.join(",")
						},
						"success" : function(resp) {
							if(resp==true){
								util.showModal("#_confirmModal", "您确定要删除选中的记录？", "_confirmModal_yes");
							}else{
								util.showModal("#_alertModal", "所选记录包含已关联电池或厂区客户,请重新选择！");
							}
							
						}
					});
				}
			});
			
			$("#_confirmModal").on('click', '#_confirmModal_yes', function() {
				var d = [];
				d = util.getCheckedData("customer_table");
				var idArray=[];
				for (var i=0;i<d.length;i++) {
					idArray.push(d[i].pkId);
				}
				var table = $('#customer_table').DataTable();
				var selRows = table.rows('.selected');
				$.ajax({
					"type" : "post",
					"url" : "main/customer/delete.mvc",
					"dataType" : "json",
					"async":false,
					"data" : {
						"pkId" : idArray.join(",")
					},
					"success" : function(resp) {
						if(resp.msg=='SUCCESS'){
							rmsBox.notify('success', {msg: '删除成功！'});
							selRows.remove();
							table.draw(true);
						}else {
							rmsBox.notify('error', {msg: '删除失败！',delay:3000});
						}
					}
				});
			});
			//删除 -----end
			
			//电池关联管理点击事件
			$("#batteryCorrelation").click(function() {
				var factory = [];
				factory = util.getCheckedData("customer_table");
				if (factory.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行电池关联绑定！");
					return false;
				}
				$.ajax({
					"type" : "post",
					"url" : "main/customer/initBatteryCorrelation.mvc",
					"dataType" : "json",
					"data" : {id:factory[0].pkId},
					"success" : function(data) {
						//var factory = data.factory;
						var multiSelect = data.multiSelect;
						var i = 0;
						$('<select />', {
							 multiple: "multiple",
							 id: "batteryCorrelation_multiSelect",
							 name: "batteryCorrelation_multiSelect[]"
						}).appendTo($('#multiSelect_controls'));
						$.each(multiSelect,function(index,value){
							var selected = "";
							var enable = "";
							var style = "";
							if (multiSelect[index].selected == 'true') {
								i = i + 1;
								selected = " selected ";
							}
							if (multiSelect[index].enable == 'false') {
								enable = "（报废）";
							}
							$('#batteryCorrelation_multiSelect').append('<option value="' + multiSelect[index].packCode+ '" ' + selected + '>'+multiSelect[index].packCode+ enable +'</option>');
		          		});
						$("#batteryCorrelation_custom").text(factory[0].cusName);
						//$("#batteryCorrelation_custom").attr("title", factory.custom);
						$("#batteryCorrelation_packNum").text(i);
						$("#batteryCorrelation_pkId").val(factory[0].pkId);
						//$("#batteryCorrelation_customId").val(factory.customId);
						initMultiSelect("#batteryCorrelation_multiSelect");
						$("#batteryID-correlation").modal({show:true, keyboard:false});
					},
					"error" : function(resp) {
						util.showModal("#_alertModal", "获取该客户电池关联信息失败！");
					}
				});
			});

			//电池绑定注册取消按钮点击事件
			$("#batteryCorrelation_close").click(function() {
				$('#multiSelect_controls').html("");
			});
			//模态框关闭清空多选插件
			$("#batteryID-correlation").on('click', '.close', function(e) {
				e.preventDefault();
				$('#multiSelect_controls').html("");
			});

			//电池绑定注册保存按钮点击事件
			$("#batteryCorrelation_save").click(function() {
				debugger
				var packCodeList = $("#batteryCorrelation_multiSelect").val();
				var pkId = $("#batteryCorrelation_pkId").val();
				var packCodeNotSelected = new Array();
				$(".ms-selectable").find("li:visible").each(function(index, el) {
					var _packcode = $(this).find('span').text();
					packCodeNotSelected.push(_packcode);
				});
				var packCodeStr = "";
				if (!util.isEmpty(packCodeList)) {
					$.each(packCodeList, function(index,value){
						if (index == 0) {
							packCodeStr = packCodeList[index];
						} else {
							packCodeStr += "," + packCodeList[index];
						}
						
	          		});
				}
				var packCodeNotSelectedStr = "";
				if (!util.isEmpty(packCodeNotSelected)) {
					$.each(packCodeNotSelected, function(index,value){
						if (index == 0) {
							packCodeNotSelectedStr = packCodeNotSelected[index];
						} else {
							packCodeNotSelectedStr += "," + packCodeNotSelected[index];
						}
						
	          		});
				}
				//console.log(packCodeNotSelectedStr+'selected Not+++');
				//console.log(packCodeStr+'selected+++')
				$.ajax({
					"type" : "post",
					"url" : "main/customer/saveBatteryCorrelation.mvc",
					"dataType" : "json",
					"data" : {
						'pkId': pkId,
						'packCode' : packCodeStr,
						'packCodeNot': packCodeNotSelectedStr
					},
					"success" : function(resp) {
						$("#batteryCorrelation_close").click();
						rmsBox.notify('success', {msg: '操作成功！'});
					},
					"error" : function(resp) {
						$("#batteryCorrelation_close").click();
						rmsBox.notify('error', {msg: '操作失败！',delay:3000});
					}
				});
			});

			//初始化两边多选择插件
			function initMultiSelect(selector) {
				$(selector).multiSelect({
				  selectableHeader: "<input type='text' style='width:205px;' autocomplete='off' placeholder='搜索...'>",
				  selectionHeader: "<input type='text' style='width:205px;' autocomplete='off' placeholder='搜索...'>",
				  afterInit: function(ms){
				    var that = this,
				        $selectableSearch = that.$selectableUl.prev(),
				        $selectionSearch = that.$selectionUl.prev(),
				        selectableSearchString = '#'+that.$container.attr('id')+' .ms-elem-selectable:not(.ms-selected)',
				        selectionSearchString = '#'+that.$container.attr('id')+' .ms-elem-selection.ms-selected';
				    that.qs1 = $selectableSearch.quicksearch(selectableSearchString)
				    .on('keydown', function(e){
				      if (e.which === 40){
				        that.$selectableUl.focus();
				        return false;
				      }
				    });

				    that.qs2 = $selectionSearch.quicksearch(selectionSearchString)
				    .on('keydown', function(e){
				      if (e.which == 40){
				        that.$selectionUl.focus();
				        return false;
				      }
				    });
				  },
				  afterSelect: function(){
				    this.qs1.cache();
				    this.qs2.cache();
				  },
				  afterDeselect: function(){
				    this.qs1.cache();
				    this.qs2.cache();
				  }
				});
			};
			
			/*
			 * 获取编辑对象
			 * @param id 主键id
			 */
			function getCustomerById(id){
				var data = [];
				$.ajax({
					"type" : "post",
					"url" : "main/customer/getCustomerById.mvc",
					"dataType" : "json",
					"async":false,
					"data" : {
						"pkId" : id
					},
					"success" : function(resp) {
						data = resp;
					}
				});
				return data;
			}
			
		}
	};
}();
